package com.hadluo.qq.client.ui;

import com.formdev.flatlaf.FlatDarkLaf;
import com.hadluo.qq.client.model.LoginResponse;
import com.hadluo.qq.client.utils.Constants;
import com.hadluo.qq.client.utils.ConfigManager;
import com.hadluo.qq.client.utils.HttpClient;

import javax.swing.*;
import java.awt.*;

/**
 * QQ登录窗口
 * @author hadluo
 */
public class LoginFrame extends JFrame {
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JButton loginButton;
    private JButton registerButton;


    public void setPassword(String password) {
        if (passwordField != null) {
            passwordField.setText(password);
        }
    }

    private void loadSavedLoginInfo() {
        String savedQQNumber = ConfigManager.getSavedQQNumber();
        String savedPassword = ConfigManager.getSavedPassword();

        if (savedQQNumber != null && !savedQQNumber.isEmpty()) {
            setQQNumber(savedQQNumber);
        }
        if (savedPassword != null && !savedPassword.isEmpty()) {
            setPassword(savedPassword);
        }
    }

    public LoginFrame() {
        initializeUI();
        // 加载历史登录信息
        loadSavedLoginInfo();
    }

    private void initializeUI() {
        // 设置窗口基本属性
        setTitle("Chat");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 350);
        setLocationRelativeTo(null);
        setResizable(false);

        // 创建主面板
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout(0, 15));
        mainPanel.setBackground(new Color(235, 235, 235));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 30, 20, 30));

        // 创建Logo面板
        JPanel logoPanel = new JPanel();
        logoPanel.setBackground(new Color(235, 235, 235));
        JLabel logoLabel = new JLabel("Let Me Chat!!!");
        logoLabel.setFont(new Font("微软雅黑", Font.BOLD, 36));
        logoLabel.setForeground(new Color(0, 120, 215));
        logoPanel.add(logoLabel);

        // 创建输入面板
        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(new GridBagLayout());
        inputPanel.setBackground(new Color(235, 235, 235));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(5, 0, 5, 0);
        gbc.weightx = 1.0;

        // 用户名输入
        JPanel userPanel = new JPanel(new BorderLayout(10, 0));
        userPanel.setBackground(new Color(235, 235, 235));
        JLabel usernameLabel = new JLabel("账号:");
        usernameLabel.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        usernameField = new JTextField();
        usernameField.setPreferredSize(new Dimension(200, 40));
        styleTextField(usernameField);
        userPanel.add(usernameLabel, BorderLayout.WEST);
        userPanel.add(usernameField, BorderLayout.CENTER);

        gbc.gridx = 0;
        gbc.gridy = 0;
        inputPanel.add(userPanel, gbc);

        // 密码输入
        JPanel passPanel = new JPanel(new BorderLayout(10, 0));
        passPanel.setBackground(new Color(235, 235, 235));
        JLabel passwordLabel = new JLabel("密码:");
        passwordLabel.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        passwordField = new JPasswordField();
        passwordField.setPreferredSize(new Dimension(200, 40));
        styleTextField(passwordField);
        passPanel.add(passwordLabel, BorderLayout.WEST);
        passPanel.add(passwordField, BorderLayout.CENTER);

        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.insets = new Insets(8, 0, 15, 0); // 增加与按钮的间距
        inputPanel.add(passPanel, gbc);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new GridLayout(2, 1, 0, 12));
        buttonPanel.setBackground(new Color(235, 235, 235));

        loginButton = new JButton("登  录");
        registerButton = new JButton("注  册");

        styleButton(loginButton);
        styleButton(registerButton);

        loginButton.addActionListener(e -> handleLogin());
        registerButton.addActionListener(e -> handleRegister());

        buttonPanel.add(loginButton);
        buttonPanel.add(registerButton);

        // 组装界面
        mainPanel.add(logoPanel, BorderLayout.NORTH);
        mainPanel.add(inputPanel, BorderLayout.CENTER);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        setContentPane(mainPanel);
    }

    private void styleTextField(JTextField textField) {
        textField.setBackground(Color.WHITE);
        textField.setForeground(Color.BLACK);
        textField.setCaretColor(Color.BLACK);
        textField.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        textField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(200, 200, 200)),
                BorderFactory.createEmptyBorder(2, 5, 2, 5)
        ));
    }

    private void styleButton(JButton button) {
        button.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        button.setFocusPainted(false);

        if (button == loginButton) {
            button.setBackground(new Color(0, 120, 215));
            button.setForeground(Color.WHITE);
        } else {
            button.setBackground(new Color(235, 235, 235));
            button.setForeground(new Color(0, 120, 215));
        }

        button.setBorder(button == loginButton ?
                BorderFactory.createLineBorder(new Color(0, 120, 215), 1) :
                BorderFactory.createLineBorder(new Color(200, 200, 200), 1));
        button.setPreferredSize(new Dimension(180, 35));

        button.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                if (button == loginButton) {
                    button.setBackground(new Color(0, 100, 200));
                } else {
                    button.setBackground(new Color(245, 245, 245));
                }
            }

            public void mouseExited(java.awt.event.MouseEvent evt) {
                if (button == loginButton) {
                    button.setBackground(new Color(0, 120, 215));
                } else {
                    button.setBackground(new Color(235, 235, 235));
                }
            }
        });
    }

    private void handleLogin() {
        String username = usernameField.getText();
        String password = new String(passwordField.getPassword());

        if (username.isEmpty() || password.isEmpty()) {
            JOptionPane.showMessageDialog(this,
                    "用户名和密码不能为空",
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 禁用登录按钮，防止重复点击
        loginButton.setEnabled(false);
        loginButton.setText("登录中...");

        // 在新线程中执行登录请求
        new Thread(() -> {
            try {
                LoginResponse response = HttpClient.login(username, password);

                // 在EDT中处理响应
                SwingUtilities.invokeLater(() -> {
                    if (response.isSuccess()) {
                        // 登录成功，直接关闭登录窗口
                        dispose();

                        // 打开主界面
                        MainFrame mainFrame = new MainFrame(response.getUserInfo());
                        mainFrame.setVisible(true);
                    } else {
                        // 登录失败
                        JOptionPane.showMessageDialog(this,
                                response.getMessage(),
                                "登录失败",
                                JOptionPane.ERROR_MESSAGE);
                    }

                    // 恢复登录按钮状态
                    loginButton.setEnabled(true);
                    loginButton.setText("登  录");
                });
            } catch (Exception e) {
                // 在EDT中处理错误
                SwingUtilities.invokeLater(() -> {
                    JOptionPane.showMessageDialog(LoginFrame.this,
                            "连接服务器失败：" + e.getMessage(),
                            "错误",
                            JOptionPane.ERROR_MESSAGE);

                    // 恢复登录按钮状态
                    loginButton.setEnabled(true);
                    loginButton.setText("登  录");
                });
            }
        }).start();
    }

    private void handleRegister() {
        RegisterFrame registerFrame = new RegisterFrame();
        registerFrame.setVisible(true);
    }

    public void setQQNumber(String qqNumber) {
        usernameField.setText(qqNumber);
    }

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(new FlatDarkLaf());
        } catch (Exception e) {
            e.printStackTrace();
        }

        SwingUtilities.invokeLater(() -> {
            LoginFrame loginFrame = new LoginFrame();
            loginFrame.setVisible(true);
        });
    }
}